// 获取组件名称
export const getComponentDisplayName = (component) => {
  return component.displayName || component.name || 'Component';
}

// 获取tree节点路径
export const findPathFromTree = (tree, func, path = []) => {
  if (!tree) return [];
  for (let data of tree) {
    const node = { ...data };
    Reflect.deleteProperty(node, 'children');
    path.push(node);
    if (func(data)) return path;
    if (data.children) {
      const findChildren = findPathFromTree(data.children, func, path);
      if (findChildren.length) return findChildren;
    }
    path.pop();
  }
  return [];
};

// 过滤树
export const filterTree = (tree = [], validate = () => {}, param = [], arr = []) => {
  if (!tree.length) return [];
  for (let item of tree) {
    if (!validate.apply(null, [item, ...param])) continue;
    let node = { ...item, children: [] };
    arr.push(node);
    if (item.children && item.children.length)
      filterTree(item.children, validate, param, node.children);
  }
  return arr;
};

// 格式化树
export const formatTree = (tree = [], fn, arr = []) => {
  if (!tree.length || !fn) return [];
  for (let item of tree) {
    let node = { ...fn(item) };
    if (item.children && item.children.length) {
      node.children = [];
      arr.push(node);
      formatTree(item.children, fn, node.children);
    } else {
      arr.push(node);
    }
  }
  return arr;
};

// 构建树
export const generateTree = (list = [], pid = 'parentId') => {
  // * 先生成parent建立父子关系
  const obj = {};
  list.forEach((item) => {
    obj[item.value] = item;
  });
  const parentList = [];
  list.forEach((item) => {
    const parent = obj[item[pid]];
    if (parent) {
      parent.children = parent.children || [];
      parent.children.push(item);
    } else {
      parentList.push(item);
    }
  });
  return parentList;
};

// 获取密码等级
export const passwordGrade = (pwd) => {
  let score = 0;
  let repeatCount = 0;
  let prevChar = '';
  const len = pwd.length;
  const strengthSteps = [10, 20, 30, 40];
  const regexArr = ['[0-9]', '[a-z]', '[A-Z]', '[\\W_]'];

  score += len > 18 ? 18 : len;
  for (let i = 0, num = regexArr.length; i < num; i++) {
    if (eval('/' + regexArr[i] + '/').test(pwd)) score += 4;
  }
  for (let i = 0, num = regexArr.length; i < num; i++) {
    if (
      pwd.match(eval('/' + regexArr[i] + '/g')) &&
      pwd.match(eval('/' + regexArr[i] + '/g')).length >= 2
    )
      score += 2;
    if (
      pwd.match(eval('/' + regexArr[i] + '/g')) &&
      pwd.match(eval('/' + regexArr[i] + '/g')).length >= 5
    )
      score += 2;
  }
  for (let i = 0, num = pwd.length; i < num; i++) {
    if (pwd.charAt(i) == prevChar) repeatCount++;
    else prevChar = pwd.charAt(i);
  }

  score -= repeatCount;
  const grade = _.findIndex(strengthSteps, (v) => v >= score) + 1 || 5;

  return { score, grade };
};
